using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using PocketPals.Data;
using PocketPals.Models;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace PocketPals.Controllers
{
    /// <summary>
    /// 交易记录控制器
    /// </summary>

    [Authorize]
    public class TransactionController : Controller
    {
        private readonly ApplicationDbContext _context;

        public TransactionController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 显示交易记录列表
        /// </summary>
        /// <returns>交易记录列表视图</returns>
        public async Task<IActionResult> Index()
        {
            var transactions = await _context.Transactions
                .OrderByDescending(t => t.TransactionTime)
                .ToListAsync();

            // 获取当前余额
            var currentBalance = await _context.Balances
                .OrderByDescending(b => b.UpdatedAt)
                .Select(b => b.Amount) // 只选择金额字段
                .FirstOrDefaultAsync(); // 获取最新的一个

            // 将余额传递给视图
            ViewBag.CurrentBalance = currentBalance; // 如果没有余额记录，默认为 0

            return View(transactions);
        }

        /// <summary>
        /// 显示创建新交易记录的表单
        /// </summary>
        /// <returns>创建交易记录视图</returns>
        public IActionResult Create()
        {
            // 准备交易类型下拉列表
            ViewBag.TransactionTypes = new SelectList(
                Enum.GetValues(typeof(TransactionType))
                    .Cast<TransactionType>()
                    .Select(t => new { Value = (int)t, Text = t.ToString() }),
                "Value", "Text");

            return View(new Transaction
            {
                TransactionTime = DateTime.UtcNow.AddHours(8),
                CreatedAt = DateTime.UtcNow.AddHours(8),
                UpdatedAt = DateTime.UtcNow.AddHours(8)
            });
        }

        /// <summary>
        /// 处理创建新交易记录的请求
        /// </summary>
        /// <param name="transaction">交易记录对象</param>
        /// <returns>重定向到交易记录列表</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Transaction transaction)
        {
            if (ModelState.IsValid)
            {
                // 设置交易记录的ID和时间戳
                transaction.Id = Guid.NewGuid();
                transaction.CreatedAt = DateTime.UtcNow.AddHours(8);
                transaction.UpdatedAt = DateTime.UtcNow.AddHours(8);
                transaction.TransactionTime = DateTime.UtcNow.AddHours(8);

                // 获取当前余额
                var balance = await _context.Balances
                    .OrderByDescending(b => b.UpdatedAt)
                    .FirstOrDefaultAsync();

                if (balance == null)
                {
                    // 如果没有余额记录，创建一个新的
                    balance = new Balance
                    {
                        Id = Guid.NewGuid(),
                        Amount = 0,
                        UpdatedAt = DateTime.UtcNow.AddHours(8)
                    };
                    _context.Balances.Add(balance);
                }

                // 计算新的余额
                decimal beforeAmount = balance.Amount;
                decimal operationAmount = transaction.Type == TransactionType.Income 
                    ? transaction.Amount 
                    : -transaction.Amount;
                decimal afterAmount = beforeAmount + operationAmount;

                // 创建新的余额记录
                var newBalance = new Balance
                {
                    Id = Guid.NewGuid(),
                    Amount = afterAmount,
                    BeforeAmount = beforeAmount,
                    OperationAmount = operationAmount,
                    AfterAmount = afterAmount,
                    UpdatedAt = DateTime.UtcNow.AddHours(8)
                };

                // 保存交易记录和新的余额记录
                _context.Transactions.Add(transaction);
                _context.Balances.Add(newBalance);
                await _context.SaveChangesAsync();

                return RedirectToAction(nameof(Index));
            }

            // 如果模型验证失败，重新准备交易类型下拉列表
            ViewBag.TransactionTypes = new SelectList(
                Enum.GetValues(typeof(TransactionType))
                    .Cast<TransactionType>()
                    .Select(t => new { Value = (int)t, Text = t.ToString() }),
                "Value", "Text");

            return View(transaction);
        }

        /// <summary>
        /// 显示交易记录详情
        /// </summary>
        /// <param name="id">交易记录ID</param>
        /// <returns>交易记录详情视图</returns>
        public async Task<IActionResult> Details(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var transaction = await _context.Transactions
                .FirstOrDefaultAsync(m => m.Id == id);

            if (transaction == null)
            {
                return NotFound();
            }

            return View(transaction);
        }
    }
}